import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { ButtonGroup } from "@/utils/CommonComponent";
import { Icon, Input, List, Pagination, Spin,Tabs } from "antd";
import React, { Suspense } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import styles from './index.less'
import moment from "moment";
import AddLibrary from "./addLibrary";
import SortModal from "./sortModal";
import DocLibraryTag from "./DocLibraryTag";
import { docLibraryList, docLibraryListAdmin,docTagListByPage } from "@/services/knowledgeFile";

const { TabPane } = Tabs

class DocLibrary extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      search:"",
      current:1,
      size:9999,
      loading:false,
      list:[],
      total:0,
      isAdmin:false,
      sortCondition: 'createTime',
      sortType: 0,
    }
  }

  componentDidMount(){
    this.getList()
  }

  getList = () => {
    const { location } = this.props;
    this.setState({
      loading:true,
      isAdmin:location.pathname.indexOf("publicResource") != -1
    },async () => {
      const { current,size,search } = this.state;
      let res = {}
      if(location.pathname.indexOf("publicResource") != -1){
        //admin
        res = await docLibraryListAdmin({current,size,search,type:0})
      }else{
        res = await docLibraryList({current,size,search,type:0})
      }

      this.setState({
        loading:false,
        total:res.total
      })

      this.doSort({}, res.records ? res.records : [])
    })
  }

  doSearch = (current,size) => {
    this.setState({
      current,
      size
    },() => {
      this.getList()
    })
  }

  doSort = ({ sortCondition, sortType }, list = this.state.list) => {
    if (list.length < 2) {
      this.setState({
        list
      })
      return
    }
    if (sortCondition !== this.state.sortCondition || sortType !== this.state.sortType) {
      this.setState({
        sortCondition,
        sortType,
      })
    }
    if (sortCondition === 'name') {
      const locale = 'en-US'
      const newList = list.sort((a, b) => sortType === 1 ? a[sortCondition].localeCompare(b[sortCondition], locale) : b[sortCondition].localeCompare(a[sortCondition], locale))
      this.setState({
        list: newList
      })
      return
    }
    const newList = list.sort((a, b) => {
      const aVal = a[sortCondition]
      const bVal = b[sortCondition]
      if (sortType === 1) {
        if (aVal > bVal) {
          return 1
        } else if (aVal < bVal) {
          return -1
        } else {
          return 0
        }
      } else {
        if (aVal > bVal) {
          return -1
        } else if (aVal < bVal) {
          return 1
        } else {
          return 0
        }
      }
    })
    this.setState({
      list: newList
    })
  }

  openAddModal = () => {
    this.AddLibrary.initOpen()
  }

  openSortModal = () => {
    this.SortModal.initModal()
  }

  toDocSetting = (e,item) => {
    e.persist()
    e.stopPropagation();
    const { history } = this.props;
    if(this.state.isAdmin){
      history.push({ pathname: '/publicResource/documentLibrary/docLibrarySetting',query:{docLibraryId:item.id} })
    }else{
      history.push({ pathname: '/documentLibrary/docLibrarySetting',query:{docLibraryId:item.id} })
    }
  }

  toFile = (item) => {
    const { history } = this.props;
    if(this.state.isAdmin){
      history.push({ pathname: `/publicResource/documentLibrary/${item.id}/file`,query:{} })
    }else{
      history.push({ pathname: `/documentLibrary/${item.id}/file`,query:{} })
    }

  }

  handleClick = e => {
    this.setState({
      current: e.key,
    });
  }

  render(){
    const { search,current,size,loading,list,total,isAdmin } = this.state
    return(
      <div>
        <Tabs defaultActiveKey="1">

          <TabPane tab={formatMessage({id: 'knowledgeFile.docLibrary.tabs.docLibrary'})} key="1">
            <Suspense fallback={<PageLoading />}>
              <PageHeaderWrapper>
                <div style={{minHeight:'100%',background:"#ffffff"}}>
                  <div className="topOptionBox" style={{padding:"10px"}}>
                    <div>
                      <Input.Search
                        placeholder={formatMessage({id: 'knowledgeFile.docLibrary.search.placeholder'})}
                        value={search}
                        onChange={e => this.setState({search:e.target.value})}
                        onSearch={() => this.doSearch(1,size)}
                      />
                    </div>
                    {
                      isAdmin ? '' : (
                          <div>
                            <ButtonGroup
                                title={formatMessage({id: 'knowledgeFile.docLibrary.buttons.addLibrary'})}
                                group="add"
                                handleClick={() => this.openAddModal()}
                            />
                            <ButtonGroup
                                title={formatMessage({id: 'knowledgeFile.docLibrary.buttons.sort'})}
                                group="sort"
                                handleClick={() => this.openSortModal()}
                                style={{marginRight:0}}
                            />
                          </div>
                      )
                    }
                  </div>

                  <Spin spinning={loading}></Spin>

                  <div className={styles.libraryContainer}>
                    {
                      list.map(item => {
                        return (
                            <div className={styles.gridItem} onClick={() => this.toFile(item)} key={item.id}>
                              <div className={styles.gridBg} style={{background:item.libraryBackground}}>
                                {item.permissionType == 1 ? <img src={item.libraryBackground} /> : null}
                              </div>
                              <h3 className={styles.docName} style={{ WebkitBoxOrient: 'vertical' }}>{item.name}</h3>
                              <p className={styles.intro} title={item.libraryIntroduction} style={{ WebkitBoxOrient: 'vertical' }}>{item.libraryIntroduction}</p>
                              {item.permissionType == 1 ? <div className={styles.isShared}>{formatMessage({id: 'knowledgeFile.docLibrary.public.text'})}</div> : ''}
                              {
                                item.isShowSysSetting || isAdmin ? <div className={styles.settingBox} onClick={e => this.toDocSetting(e,item)}><Icon type="setting" /><span>{formatMessage({id: 'knowledgeFile.docLibrary.settingsLink'})}</span></div> : ''

                              }

                            </div>
                        )
                      })
                    }

                  </div>

                  {parseInt(total) > size ? (<Pagination
                      pageSize={size}
                      total={total}
                      current={current}
                      onChange={this.doSearch}
                      showQuickJumper={true}
                      style={{ marginTop: 20, textAlign: 'center' }}
                  />):''}

                  <AddLibrary onRef={ref => this.AddLibrary = ref} refreshList={() => this.doSearch(1,size)} />
                  <SortModal onRef={ref => this.SortModal = ref} sort={this.doSort} />
                </div>
              </PageHeaderWrapper>

            </Suspense>

          </TabPane>
          <TabPane tab={formatMessage({id: 'knowledgeFile.docLibrary.tabs.docLibraryTag'})} key="2">
            <DocLibraryTag />

          </TabPane>
        </Tabs>
      </div>
    )
  }
}

export default DocLibrary
